import java.util.Arrays;
import java.util.Comparator;

/**
 * 使用 Comparable 接口比较
 * 要重写 compareTo方法
 */
class Student implements Comparable<Student>{
    public int age;
    public String name;
    public Student(int age, String name){
        this.age = age;
        this.name = name;
    }

    @Override
    public int compareTo(Student o) {
        return this.age - o.age;
    }

    @Override
    public String toString() {
        return "student{" + "name="+name+",age=" + age+'}';
    }
}

/**
 * 使用 Comparator 比较器比较
 * 需要单独创建一个类实现接口
 * 要重写 compare方法
 */
class AgeComparator implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}

class NameComparator implements Comparator<Student>{
    @Override
    public int compare(Student o1, Student o2) {
        //String类中实现了Comparator 接口可以使用compareTo方法
        return o1.name.compareTo(o2.name);
    }
}
public class Test {
    public static void main(String[] args) {
        Student[] s = new Student[3];
        s[0] = new Student(5,"efg");
        s[1] = new Student(10,"abc");
        s[2] = new Student(4,"cba");
        /*Arrays.sort(s);*/
        System.out.println(Arrays.toString(s));
        /**
         * 按年龄比较
         */
        AgeComparator ageComparator = new AgeComparator();
        Arrays.sort(s,ageComparator);
        System.out.println(Arrays.toString(s));
        /**
         * 按名字比较
         */
        NameComparator nameComparator = new NameComparator();
        Arrays.sort(s,nameComparator);
        System.out.println(Arrays.toString(s));

    }
}
